package com.kuang.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * @author luomingliang
 * @date 2021/5/25 22:00
 */
public class ForkJoinDemo extends RecursiveTask<Long> {
    /**
     * 求和计算的任务！
     * 3000 6000(ForkJoin) 9000(Stream并行流）
     *  如何使用ForkJoin？
     *      1、ForkJoinPool  通过他来执行
     *      2、计算任务 ForkJoinPool.execute(ForkJoinTask<?> task)
     *      3、计算类继承RecursiveTask<V>类
     */
    private long start;
    private long end;
    //临界值
    private long temp = 10000L;

    public ForkJoinDemo(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if ((end - start)<temp) {
            long sum = 0L;
            for (long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        } else { //forkjoin
            long middle = (start + end) / 2; //中间值
            ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
            task1.fork(); //拆分任务，把任务压入线程队列
            ForkJoinDemo task2 = new ForkJoinDemo(middle+1, end);
            task2.fork();
            return task1.join() + task2.join();
        }
    }
}
